<template>
    <div class="bigbox">
        <div class="box">
            <!-- 滑动盒子 -->
            <div class="pre-box" ref="preRef">
                <h1>欢迎</h1>
                <p>加入我们！！！</p>
                <div class="img-box">
                    <img src="https://tse1-mm.cn.bing.net/th/id/OIP-C.GZRq-oAvpHwVbsRHxu751gAAAA?rs=1&pid=ImgDetMain"
                        alt="">
                </div>
            </div>
            <!-- 注册盒子 -->
            <div class="register-form">
                <div class="title-box">
                    <h1>注册</h1>
                </div>
                <div class="input-box">
                    <input type="text" v-model="id" placeholder="学号ID" @input="checkId" />
                    <p v-if="errorId" class="error-message">字母/数字(不能为空)</p>
                    <input type="text" v-model="userName" placeholder="用户名" @input="checkName" />
                    <p v-if="errorName" class="error-message">只能输入中文</p>
                    <input type="text" v-model="password" placeholder="密码" @input="checkpassword" />
                    <p v-if="errorPassword" class="error-message">字母/数字(6-16位)</p>
                    <input type="text" v-model="email" placeholder="邮箱" @input="checkemail" />
                    <p v-if="errorEmail" class="error-message">邮箱格式错误</p>
                </div>
                <div class="btn-box">
                    <button @click="submitToDatabase">注册</button>
                    <p @click="mySwitch">已有账号?去登录</p>
                </div>
            </div>
            <!--输入框盒子   -->


            <!-- 登录盒子 -->
            <div class="login-form">
                <div class="title-box">
                    <h1>登录</h1>
                </div>
                <div class="input-box">
                    <input type="text" v-model="id_login" placeholder="学号ID" />
                    <input type="password" v-model="password_login" placeholder="密码" />
                </div>
                <div class="btn-box">
                    <button @click="login">登录</button>
                    <p @click="mySwitch">没有账号?去注册</p>
                    <!-- <div v-if="loginResult">{{ loginResult }}</div> -->
                </div>
            </div>




            <!-- 登录结果显示（示例） -->

        </div>
        <!-- <div v-for="(answerItem, index) in  answer " :key="index">
        <p>{{ answerItem.userName }}</p>
      </div> -->

    </div>
</template>

<!-- <div v-for="(answerItem, index) in answers" :key="index">
            <p>Id: {{ answerItem.id }}</p>
            <p>userName: {{ answerItem.userName }}</p>
            <p>password: {{ answerItem.password }}</p>
            <p>email: {{ answerItem.email }}</p>
        </div> -->
<script setup>
    import { ref, onMounted, inject, provide } from 'vue';
    import { useRouter } from 'vue-router'
    const url = 'http://119.28.50.240:3000/api/register';
    // const url = 'http://localhost:3000/api/register';
    // const url_login = 'http://localhost:3000/api/login';

    const login_answer = ref([])
    const answers = ref([]);
    const answer_login = ref([]);
    const id = ref('');
    const userName = ref('');
    const password = ref('');
    const email = ref('');
    const preRef = ref('');
    const flag = ref(true);

    const id_login = ref('');
    const password_login = ref('');
    const loginResult = ref(''); // 用于显示登录结果 
    // const userlogin=ref('');

    //检测的变量
    const errorName = ref(false);
    const errorId = ref(false);
    const errorPassword = ref(false);
    const errorEmail = ref(false);


    const loginitem = inject('loginitem');
    const iflogin = inject('iflogin');


    // provide('id_login', id_login);
    //检测账号的函数
    function checkName() {
        const chineseRegex = /^[\u4e00-\u9fa5]+$/;
        if (!chineseRegex.test(userName.value)) {
            userName.value = userName.value.replace(/[^\u4e00-\u9fa5]/g, '');
            errorName.value = true;
        } else {
            errorName.value = false;
        }
    }
    //检测id的函数
    function checkId() {
        const accountRegex = /^[a-zA-Z0-9]+$/; // 只允许字母和数字  
        if (!accountRegex.test(id.value)) {
            errorId.value = true;
        } else {
            errorId.value = false;
        }
    }
    //检测密码的函数
    function checkpassword() {
        const passwordRegex = /^[a-zA-Z0-9]{6,16}$/; // 只允许字母和数字，长度在6到16之间  
        if (!passwordRegex.test(password.value)) {
            errorPassword.value = true;
        } else {
            errorPassword.value = false;
        }
    }
    //检测邮箱的函数
    function checkemail() {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email.value)) {
            errorEmail.value = true;
        } else {
            errorEmail.value = false;
        }
    }

    const router = useRouter();
    const submitToDatabase = async () => {
        if (!userName.value || !id.value || !password.value || !email.value) {
            console.error('输入不能为空')
            errorName.value = true;
            errorId.value = true;
            errorPassword.value = true;
            errorEmail.value = true;
            return;
        }
        if (!id.value) {
            console.error('id不能为空')
        }
        if (!userName.value) {
            console.error('用户名不能为空')
        }
        if (!password.value) {
            console.error('密码不能为空')
        }
        if (!email.value) {
            console.error('邮箱不能为空')
        }

        try {
            const formData = {
                id: id.value,
                userName: userName.value,
                password: password.value,
                email: email.value,
            };
            // const response = await fetch('http://119.28.50.240:3000/api/register', {
            //   method: 'POST',
            //   headers: {
            //     'Content-Type': 'application/json'
            //   },
            //   body: JSON.stringify(formData)
            // });
            const response = await fetch('http://119.28.50.240:3000/api/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });
            if (!response.ok) {
                throw new Error('Failed to submit data');
            }
            const data = await response.json();
            console.log('Data submitted successfully:', data);
            id.value = '';
            userName.value = '';
            password.value = '';
            email.value = '';
            preRef.value.style.transform = 'translateX(0)';
            preRef.value.style.background = 'rgb(191, 227, 241)';
            flag.value = true;
            alert('账号注册成功');
        } catch (error) {
            console.error('账号已注册', error);
            alert('账号已注册');
        }
    };

    const login = async () => {
        try {
            const formData = {
                id: id_login.value,
                password: password_login.value,
            };

            const response = await fetch('http://119.28.50.240:3000/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                throw new Error('Failed to login');
            }

            const data = await response.json();
            loginResult.value = data.message; // 显示登录结果  
            login_answer.value = data.data;
            console.log(login_answer.value);
            console.log(loginResult.value);
            // 假设登录成功后，服务器会返回一些用户信息，你可以将这些信息存储到本地或进行其他操作 
            if (loginResult.value == "登录成功") {
                router.push('/home');
                iflogin.value = false;
                loginitem.value = false;
            }

            // 在这里可以根据登录结果执行其他操作，如跳转到其他页面等  
        } catch (error) {
            console.error('Error logging in:', error);
            loginResult.value = 'Error logging in'; // 显示错误消息  
        }
    };


    onMounted(async () => {
        try {
            const response = await fetch(url); // 使用 fetch 替代 XMLHttpRequest  
            // const response_login = await fetch(url_login);
            if (!response.ok) {
                throw new Error('Failed to fetch data');
            }
            const data = await response.json();
            // const data_login = await response_login.json();
            // answer_login.value = data_login.data;
            if (data.code === 200 && data.data) {
                answers.value = data.data; // 将获取到的 Answers 数组赋值给 answers  
            } else {
                console.error('获取数据失败', data.message);
            }

            response.value = data.id;
        } catch (error) {
            console.error('发生错误:', error);
        }
    });
    console.log(answers);
    console.log(answer_login)



    //这是针对滑动盒子


    const mySwitch = () => {
        if (flag.value) {
            preRef.value.style.transform = 'translateX(100%)';
            preRef.value.style.background = 'rgb(247, 209, 215)';
            flag.value = false;
        } else {
            preRef.value.style.transform = 'translateX(0)';
            preRef.value.style.background = 'rgb(191, 227, 241)';
            flag.value = true;
        }
    }
</script>


<style scoped>
    input {
        outline: none;
    }

    .bigbox {
        /* 溢出隐藏 */
        height: 100vh;
        overflow-x: hidden;
        display: flex;
        /* 渐变方向从左到右 */
        background: linear-gradient(to right, rgb(247, 209, 215), rgb(191, 227, 241));
    }

    span {
        position: absolute;
        z-index: 0;
        bottom: 0;
        border-radius: 50%;
        /* 径向渐变 */
        background: radial-gradient(circle at 72% 28%, #fff 3px, #ff7edf 8%, #5b5b5b, #aad7f9 100%);
        /* 泡泡内阴影 */
        box-shadow: inset 0 0 6px #fff,
            inset 3px 0 6px #eaf5fc,
            inset 2px -2px 10px #efcde6,
            inset 0 0 60px #f9f6de,
            0 0 20px #fff;
        /* 动画 */
        animation: myMove 4s linear infinite;
    }


    @keyframes myMove {
        0% {
            transform: translateY(0%);
            opacity: 1;
        }

        50% {
            transform: translate(10%, -1000%);
        }

        75% {
            transform: translate(-20%, -1200%);
        }

        99% {
            opacity: .9;
        }

        100% {
            transform: translateY(-1800%) scale(1.5);
            opacity: 0;
        }
    }

    /* 最外层的大盒子 */
    .box {
        width: 1050px;
        height: 600px;
        display: flex;
        /* 相对定位 */
        position: relative;
        z-index: 2;
        margin: auto;
        /* 设置圆角 */
        border-radius: 8px;
        /* 设置边框 */
        border: 1px solid rgba(255, 255, 255, .6);
        /* 设置盒子阴影 */
        box-shadow: 2px 1px 19px rgba(0, 0, 0, .1);
    }

    /* 滑动的盒子 */
    .pre-box {
        /* 宽度为大盒子的一半 */
        width: 50%;
        /* width: var(--width); */
        height: 100%;
        /* 绝对定位 */
        position: absolute;
        /* 距离大盒子左侧为0 */
        left: 0;
        /* 距离大盒子顶部为0 */
        top: 0;
        z-index: 99;
        border-radius: 4px;
        background-color: #edd4dc;
        box-shadow: 2px 1px 19px rgba(0, 0, 0, .1);
        /* 动画过渡，先加速再减速 */
        transition: 0.5s ease-in-out;
    }

    /* 滑动盒子的标题 */
    .pre-box h1 {
        margin-top: 150px;
        text-align: center;
        /* 文字间距 */
        letter-spacing: 5px;
        color: white;
        /* 禁止选中 */
        user-select: none;
        /* 文字阴影 */
        text-shadow: 4px 4px 3px rgba(0, 0, 0, .1);
    }

    /* 滑动盒子的文字 */
    .pre-box p {
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin: 20px 0;
        /* 禁止选中 */
        user-select: none;
        font-weight: bold;
        color: white;
        text-shadow: 4px 4px 3px rgba(0, 0, 0, .1);
    }

    /* 图片盒子 */
    .img-box {
        width: 200px;
        height: 200px;
        margin: 20px auto;
        /* 设置为圆形 */
        border-radius: 50%;
        /* 设置用户禁止选中 */
        user-select: none;
        overflow: hidden;
        box-shadow: 4px 4px 3px rgba(0, 0, 0, .1);
    }

    /* 图片 */
    .img-box img {
        width: 100%;
        transition: 0.5s;
    }

    /* 登录和注册盒子 */
    .login-form,
    .register-form {
        flex: 1;
        height: 100%;
    }

    /* 标题盒子 */
    .title-box {
        height: 240px;
        line-height: 280px;

    }

    /* 标题 */
    .title-box h1 {
        text-align: center;
        color: white;
        /* 禁止选中 */
        user-select: none;
        letter-spacing: 5px;
        text-shadow: 4px 4px 3px rgba(0, 0, 0, .1);

    }

    /* 输入框盒子 */
    .input-box {
        height: 280px;
        display: flex;
        /* 纵向布局 */
        flex-direction: column;
        /* 水平居中 */
        align-items: center;
    }


    /* 输入框 */
    input {
        width: 60%;
        height: 40px;
        /* margin-top: 10px; */
        text-indent: 10px;
        border: 1px solid #fff;
        background-color: rgba(255, 255, 255, 0.3);
        border-radius: 120px;
        /* 增加磨砂质感 */
        backdrop-filter: blur(10px);
    }

    .input-box p {
        /* border: #ff0000 solid 1px; */
        /* height: 10px; */
        /* font-size: 0.93rem; */
        margin-top: 0;
        margin-bottom: 0;
        color: red;
    }

    input:nth-child(2) {
        /* border: red 1px solid; */
        margin-top: 10px;
    }

    input:nth-child(3) {
        margin-top: 10px;
    }

    input:nth-child(4) {
        /* border: red 1px solid; */
        margin-top: 10px;
        margin-bottom: 10px;
    }

    input:focus {
        /* 光标颜色 */
        color: #b0cfe9;

    }

    /* 聚焦时隐藏文字 */
    input:focus::placeholder {
        opacity: 0;
    }

    /* 按钮盒子 */
    .btn-box {
        display: flex;
        justify-content: center;
    }

    /* 按钮 */
    button {
        width: 100px;
        height: 30px;
        margin: 10px 10px;
        line-height: 30px;
        border: none;
        border-radius: 4px;
        background-color: #69b3f0;
        color: white;
    }

    /* 按钮悬停时 */
    button:hover {
        /* 鼠标小手 */
        cursor: pointer;
        /* 透明度 */
        opacity: .8;
    }

    /* 按钮文字 */
    .btn-box p {
        height: 30px;
        line-height: 30px;
        /* 禁止选中 */
        user-select: none;
        font-size: 14px;
        color: white;

    }

    .btn-box p:hover {
        cursor: pointer;
        border-bottom: 1px solid white;
    }
</style>



<!-- 
  import { ref, inject } from 'vue';
  const loginitem = inject('loginitem');
  const iflogin = inject('iflogin');
  router.push('/home');
  iflogin.value = false;
  loginitem.value = false; -->